import React, { useState, useCallback } from 'react';
import { usePromise } from '@/hooks/async';
import TaskState from '@/components/TaskState';

import styles from './usePromise.css';

function ajaxMock(path: string, request: any) {
  return new Promise((resolve, reject) => {
    setTimeout(
      () =>
        resolve({
          respCode: 0,
          respDesc: 'ok',
          data: { value: Math.floor(Math.random() * 100) },
        }),
      Math.random() * 500,
    );
  });
}

function useChange() {
  const [count, setCount] = useState(0);
  const change = useCallback(() => {
    setCount(v => v + 1);
  }, []);
  return { count, change };
}

export default function UsePromise() {
  const c = useChange();
  const asMock = usePromise('ajaxMock', [c.count],
    () => ajaxMock('/ajax/api/path', { a: 1, b: 2 }),
  );
  return (
    <div className={styles.normal}>
      <h1>Page usePromise</h1>
      <div>
        <div>promise: {asMock.u}</div>
        <div>status: {asMock.p ? '进行中...' : asMock.o ? '成功执行' : '执行失败'}</div>
        <TaskState as={asMock} />
        <div>
          <button onClick={c.change}>重新执行promise creator</button>
        </div>
        <pre className={styles.json}>
          result: {asMock.o && JSON.stringify(asMock.d, null, 2)}
        </pre>
      </div>
    </div>
  );
}
